<template>
  <div class="profile-page">
    <Card title="个人信息">
      <template #extra>
        <Space>
          <Button type="primary" @click="handleEdit">
            编辑资料
          </Button>
          <Button @click="handleChangePassword">
            修改密码
          </Button>
        </Space>
      </template>

      <div class="profile-content">
        <!-- 头像展示 -->
        <div class="avatar-wrapper">
          <img 
            :src="userStore.userInfo?.avatar || '/src/assets/logo.png'"
            alt="avatar" 
            class="avatar"
          />
        </div>

        <!-- 基本信息 -->
        <Descriptions>
          <Descriptions.Item label="姓名">
            {{ userStore.userInfo?.realName }}
          </Descriptions.Item>
          <Descriptions.Item label="角色">
            {{ userStore.userInfo?.userTypeDesc }}
          </Descriptions.Item>
          <Descriptions.Item label="账号">
            {{ userStore.userInfo?.username }}
          </Descriptions.Item>
          <!-- 根据角色展示不同信息 -->
          <template v-if="isTeacher">
            <Descriptions.Item label="管理班级">
              {{ userStore.userInfo?.departmentName || '-' }}
            </Descriptions.Item>
          </template>
          <template v-if="isStudent">
            <Descriptions.Item label="所属班级">
              {{ userStore.userInfo?.departmentName || '-' }}
            </Descriptions.Item>
            <Descriptions.Item label="学号">
              {{ userStore.userInfo?.username }}
            </Descriptions.Item>
          </template>
          <template v-if="isTeacher">
            <Descriptions.Item label="工号">
              {{ userStore.userInfo?.username }}
            </Descriptions.Item>
          </template>
          <Descriptions.Item label="手机号">
            {{ userStore.userInfo?.phone || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="邮箱">
            {{ userStore.userInfo?.email || '-' }}
          </Descriptions.Item>
          <Descriptions.Item label="创建时间">
            {{ userStore.userInfo?.createTime || '-' }}
          </Descriptions.Item>
        </Descriptions>
      </div>
    </Card>

    <!-- 编辑弹窗 -->
    <Modal
      title="编辑个人信息"
      :open="modalVisible"
      :maskClosable="false"
      :confirm-loading="modalLoading"
      @ok="handleSubmit"
      @cancel="modalVisible = false"
      ok-text="确定",
      cancel-text="取消"
    >
      <Form
        ref="formRef"
        :model="formState"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <!-- 头像上传 -->
        <Form.Item label="头像">
          <OssUpload
            v-model:value="formState.avatar"
            dir="avatar/"
            :max-size="2"
            accept="image/*"
            @success="handleAvatarSuccess"
          />
        </Form.Item>

        <Form.Item label="姓名" name="realName">
          <Input v-model:value="formState.realName" placeholder="请输入姓名" />
        </Form.Item>

        <Form.Item label="手机号" name="phone">
          <Input v-model:value="formState.phone" placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item label="邮箱" name="email">
          <Input v-model:value="formState.email" placeholder="请输入邮箱" />
        </Form.Item>
      </Form>
    </Modal>

    <!-- 添加修改密码弹窗 -->
    <Modal
      title="修改密码"
      :open="passwordModalVisible"
      :maskClosable="false"
      :confirm-loading="passwordModalLoading"
      @ok="handlePasswordSubmit"
      @cancel="passwordModalVisible = false"
      ok-text="确定"
      cancel-text="取消"
    >
      <Form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <Form.Item label="原密码" name="oldPassword">
          <Input.Password v-model:value="passwordForm.oldPassword" placeholder="请输入原密码" />
        </Form.Item>

        <Form.Item label="新密码" name="newPassword">
          <Input.Password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
        </Form.Item>

        <Form.Item label="确认新密码" name="confirmPassword">
          <Input.Password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useUserStore } from '@/stores/user'
import { Card, Descriptions, Button, Form, Input, Modal, message, Space } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import OssUpload from '@/components/business/OssUpload.vue'
import { UserType } from '@/types/user'
import {userApi} from '@/api/modules/user'

const userStore = useUserStore()

// 编辑表单数据
interface FormState {
  realName: string
  phone: string
  email: string
  avatar?: string
}

const formRef = ref()
const formState = ref<FormState>({
  realName: userStore.userInfo?.realName || '',
  phone: userStore.userInfo?.phone || '',
  email: userStore.userInfo?.email || '',
  avatar: userStore.userInfo?.avatar
})

// 计算属性：是否为管理员
const isAdmin = computed(() => userStore.userInfo?.userType === UserType.ADMIN)
// 计算属性：是否为教师
const isTeacher = computed(() => userStore.userInfo?.userType === UserType.TEACHER)
// 计算属性：是否为学生
const isStudent = computed(() => userStore.userInfo?.userType === UserType.STUDENT)

// 表单校验规则
const formRules: Record<string, Rule[]> = {
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应为2-20个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 编辑弹窗控制
const modalVisible = ref(false)
const modalLoading = ref(false)

// 修改密码相关
const passwordModalVisible = ref(false)
const passwordModalLoading = ref(false)
const passwordFormRef = ref()

interface PasswordFormState {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

const passwordForm = ref<PasswordFormState>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码校验规则
const validateConfirmPassword = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject('请再次输入新密码')
  }
  if (value !== passwordForm.value.newPassword) {
    return Promise.reject('两次输入的密码不一致')
  }
  return Promise.resolve()
}

const passwordRules: Record<string, Rule[]> = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 打开编辑弹窗
const handleEdit = () => {
  formState.value = {
    realName: userStore.userInfo?.realName || '',
    phone: userStore.userInfo?.phone || '',
    email: userStore.userInfo?.email || '',
    avatar: userStore.userInfo?.avatar
  }
  modalVisible.value = true
}

// 处理头像上传成功
const handleAvatarSuccess = (result: any) => {
  formState.value.avatar = result.url
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true
    
    await userStore.updateCurrentUser({
      ...formState.value,
      departmentId: userStore.userInfo?.departmentId || 0
    })
    message.success('更新成功')
    modalVisible.value = false
  } catch (error) {
    console.error('更新失败:', error)
    message.error(error.message||'更新失败')
  } finally {
    modalLoading.value = false
  }
}

// 打开修改密码弹窗
const handleChangePassword = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  passwordModalVisible.value = true
}

// 提交修改密码
const handlePasswordSubmit = async () => {
  try {
    await passwordFormRef.value.validate()
    passwordModalLoading.value = true
    
    await userApi.changePassword({
      oldPassword: passwordForm.value.oldPassword,
      newPassword: passwordForm.value.newPassword
    })
    
    message.success('密码修改成功，请重新登录')
    passwordModalVisible.value = false
    
    // 退出登录
    await userStore.logout()
  } catch (error: any) {
    console.error('修改密码失败:', error)
    message.error(error.message || '修改密码失败')
  } finally {
    passwordModalLoading.value = false
  }
}
</script>

<style lang="less" scoped>
.profile-page {
  .ant-card {
    margin-bottom: 24px;
  }

  .profile-content {
    display: flex;
    gap: 24px;

    .avatar-wrapper {
      flex-shrink: 0;
      
      .avatar {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        object-fit: cover;
        border: 1px solid #eee;
      }
    }

    .ant-descriptions {
      flex: 1;
    }
  }

  :deep(.ant-descriptions-item) {
    padding-bottom: 16px;
  }
}
</style> 